package com.boc.ewr.outsrc.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.boc.ewr.bcimp.entity.Cac;
import com.boc.ewr.bcimp.service.ICacService;
import com.boc.ewr.outsrc.entity.OutsrcExpStlmtBulk;
import com.boc.ewr.util.MsgCategoryEnum;
import com.boc.ewr.util.file.enumeration.SupplementDeliveryWayEnum;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import com.boc.ewr.outsrc.entity.OutsrcExpStlmtBulk;
import com.boc.ewr.outsrc.service.IOutsrcExpStlmtBulkService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 费用结算（散投）
 * @Author: jeecg-boot
 * @Date: 2023-06-19
 * @Version: V1.0
 */
@Api(tags = "费用结算（散投）")
@RestController
@RequestMapping("/outsrc/outsrcExpStlmtBulk")
@Slf4j
public class OutsrcExpStlmtBulkController extends JeecgController<OutsrcExpStlmtBulk, IOutsrcExpStlmtBulkService> {
    @Autowired
    private IOutsrcExpStlmtBulkService outsrcExpStlmtBulkService;

    @Autowired
    private ICacService cacService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysBaseAPI sysBaseAPI;


    /**
     * 定义任务线程池
     */
    private static ExecutorService threadPool = new ThreadPoolExecutor(
            1,
            5,
            1000,
            TimeUnit.MILLISECONDS,
            new SynchronousQueue<Runnable>(),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );

    /**
     * 分页列表查询
     *
     * @param outsrcExpStlmtBulk
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "费用结算（散投）-分页列表查询")
    @ApiOperation(value = "费用结算（散投）-分页列表查询", notes = "费用结算（散投）-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<OutsrcExpStlmtBulk>> queryPageList(OutsrcExpStlmtBulk outsrcExpStlmtBulk,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        QueryWrapper<OutsrcExpStlmtBulk> queryWrapper = QueryGenerator.initQueryWrapper(outsrcExpStlmtBulk, req.getParameterMap());
        Page<OutsrcExpStlmtBulk> page = new Page<OutsrcExpStlmtBulk>(pageNo, pageSize);
        IPage<OutsrcExpStlmtBulk> pageList = outsrcExpStlmtBulkService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 根据账单号回显
     *
     * @return
     */
    //@AutoLog(value = "费用结算（散投）-分页列表查询")
    @ApiOperation(value = "费用结算（散投）-分页列表查询", notes = "费用结算（散投）-分页列表查询")
    @GetMapping(value = "/getInfoByCaNo")
    public Result<OutsrcExpStlmtBulk> getInfoByCaNo(@RequestParam(name = "caNo") String caNo) {
        List<Cac> list = cacService.list(new LambdaQueryWrapper<Cac>().eq(Cac::getCaNo, caNo));
        if (list.size()>0){
            OutsrcExpStlmtBulk outsrcExpStlmtBulk = new OutsrcExpStlmtBulk();
            Cac cac = list.get(0);
            outsrcExpStlmtBulk.setParentBranchNm(cac.getReturnBranchName());
            outsrcExpStlmtBulk.setBranchNo(cac.getBranchNo());
            outsrcExpStlmtBulk.setBranchNm(sysBaseAPI.selectAllById(cac.getBranchNo()).getDepartName());
            outsrcExpStlmtBulk.setBillType(cac.getIskey());
            outsrcExpStlmtBulk.setProtocolNo(cac.getCaProtocolNo());
            return Result.OK(outsrcExpStlmtBulk);
        }
        return null;
    }

    /**
     * 生成费用
     *
     * @param OutsrcExpStlmtBulk
     * @param req
     * @return
     */
    //@AutoLog(value = "费用结算（批量）-生成费用")
    @ApiOperation(value = "费用结算（批量）-生成费用", notes = "费用结算（批量）-生成费用")
    @GetMapping(value = "/calCost")
    public Result<List<OutsrcExpStlmtBulk>> calCost(OutsrcExpStlmtBulk OutsrcExpStlmtBulk,
                                                     HttpServletRequest req) {
        QueryWrapper<OutsrcExpStlmtBulk> queryWrapper = QueryGenerator.initQueryWrapper(OutsrcExpStlmtBulk, req.getParameterMap());
        List<OutsrcExpStlmtBulk> list = outsrcExpStlmtBulkService.list(queryWrapper);

        String username = this.getLoginUser().getUsername();
        Callable<String> call = () -> {
            log.info("费用结算 生成费用 异步任务开始 {}", Thread.currentThread().getName());

            List<OutsrcExpStlmtBulk> OutsrcExpStlmtBulkes = outsrcExpStlmtBulkService.calCost(list);
            outsrcExpStlmtBulkService.updateBatchById(OutsrcExpStlmtBulkes);
            log.info("费用结算 生成费用 异步任务结束 {}", Thread.currentThread().getName());
            this.sendMsg(username);
            return "费用结算 生成费用 成功！！！！";
        };
        threadPool.submit(call);

        return Result.OK("正在进行费用计算，请稍等...");
    }

    /**
     * 添加
     *
     * @param outsrcExpStlmtBulk
     * @return
     */
    @AutoLog(value = "费用结算（散投）-添加")
    @ApiOperation(value = "费用结算（散投）-添加", notes = "费用结算（散投）-添加")
    //@RequiresPermissions("com.boc.ewr:outsrc_exp_stlmt_bulk:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody OutsrcExpStlmtBulk outsrcExpStlmtBulk) {
        //多份账单号同一天同一录入人，选择投递方式为“交由管辖机构对账人员上门对账”为同一编号
        if (SupplementDeliveryWayEnum.DTD.getIndex().equals(outsrcExpStlmtBulk.getSupplementDeliveryWay())) {
            String redisKey = this.getRedisKey();
            Object batnumValue = redisUtil.get(redisKey);
            if (batnumValue == null || "".equals(batnumValue)) {
                long second = this.getRestSecond();
                batnumValue = this.getLoginUser().getUsername() + "-" + System.currentTimeMillis();
                redisUtil.set(redisKey, batnumValue, second);
            }
            outsrcExpStlmtBulk.setBatnum(batnumValue.toString());
        }
        outsrcExpStlmtBulkService.save(outsrcExpStlmtBulk);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param outsrcExpStlmtBulk
     * @return
     */
    @AutoLog(value = "费用结算（散投）-编辑")
    @ApiOperation(value = "费用结算（散投）-编辑", notes = "费用结算（散投）-编辑")
    //@RequiresPermissions("com.boc.ewr:outsrc_exp_stlmt_bulk:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody OutsrcExpStlmtBulk outsrcExpStlmtBulk) {
        outsrcExpStlmtBulkService.updateById(outsrcExpStlmtBulk);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "费用结算（散投）-通过id删除")
    @ApiOperation(value = "费用结算（散投）-通过id删除", notes = "费用结算（散投）-通过id删除")
    //@RequiresPermissions("com.boc.ewr:outsrc_exp_stlmt_bulk:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        outsrcExpStlmtBulkService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "费用结算（散投）-批量删除")
    @ApiOperation(value = "费用结算（散投）-批量删除", notes = "费用结算（散投）-批量删除")
    //@RequiresPermissions("com.boc.ewr:outsrc_exp_stlmt_bulk:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.outsrcExpStlmtBulkService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "费用结算（散投）-通过id查询")
    @ApiOperation(value = "费用结算（散投）-通过id查询", notes = "费用结算（散投）-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<OutsrcExpStlmtBulk> queryById(@RequestParam(name = "id", required = true) String id) {
        OutsrcExpStlmtBulk outsrcExpStlmtBulk = outsrcExpStlmtBulkService.getById(id);
        if (outsrcExpStlmtBulk == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(outsrcExpStlmtBulk);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param outsrcExpStlmtBulk
     */
    //@RequiresPermissions("com.boc.ewr:outsrc_exp_stlmt_bulk:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OutsrcExpStlmtBulk outsrcExpStlmtBulk) {
        return super.exportXls(request, outsrcExpStlmtBulk, OutsrcExpStlmtBulk.class, "费用结算（散投）");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("outsrc_exp_stlmt_bulk:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OutsrcExpStlmtBulk.class);
    }

    // 获取登录用户信息
    private LoginUser getLoginUser() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return sysUser;
    }

    private void sendMsg(String username) {
        MessageDTO messageDTO = new MessageDTO(
                "system",
                username,
                "费用结算-费用计算成功！",
                "费用结算-费用计算成功，请及时查看并导出（下载）数据",
                MsgCategoryEnum.NOTICE.getIndex()
        );
        sysBaseAPI.sendSysAnnouncement(messageDTO);
    }

    // 获取当天结束时间（单位为秒）
    private long getRestSecond() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取明天的日期时间
        LocalDateTime tomorrow = now.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        // 计算时间间隔
        long secondsRemaining = now.until(tomorrow, ChronoUnit.SECONDS);
        return secondsRemaining;
    }

    // 获取 同一天同一录入人 RedisKey
    private String getRedisKey() {
        LoginUser loginUser = this.getLoginUser();
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String format = currentDate.format(formatter);

        return loginUser.getUsername() +
                loginUser.getOrgCode() +
                format;
    }


}
